home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 16060 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.5 KB  |  63 lines

  1. Path: news.mira.net.au!news
  2. From: davidw@werple.net.au (David White)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: int (*p)[4]; (Watcom problem)
  5. Date: 9 Apr 1996 20:28:07 +1000
  6. Organization: Werple Internet, Melbourne
  7. Message-ID: <4kde3n$6s8@werple.net.au>
  8. References: <4kcd03$37j@morgoth.sfu.ca>
  9. NNTP-Posting-Host: werplez.mira.net.au
  10. Keywords: WATCOM C++ POINTER ARRAY PROBLEM
  11.  
  12. mpohores@news.sfu.ca (Michael John Pohoreski) writes:
  13.  
  14. >I came across (ARM, page 97) the following way to define
  15. >a pointer to an array:
  16. >   int (*p)[];
  17.  
  18. >(Yes, I allready know I can just do: int *p)
  19. >So I tried it in a small C++ test program: p2a.cpp
  20.  
  21. >#include <stdio.h>
  22.  
  23. >void main( void )
  24. >{
  25. >  int a[4] = { -13, 11, -7, 5 };
  26. >  int (*x)[4]; // pointer to array
  27.  
  28. >  for (int i = 0; i < 4; i++ )
  29. >  {
  30. >    (int *)x = &a[i];
  31. >    printf( "%d\n", (*x)[0] );
  32. >  }
  33. >}
  34.  
  35. >Now here's my problem:
  36. > Under Watcom 10.5, the above doesn't compile with wcl386
  37. >but it compiles under DJGPP 2.0, and Borland C++ 3.1  Anyone know why?
  38.  
  39. > Is this a bug?
  40.  
  41. It surprises me that any compiler would accept this. A 'pointer to an array'
  42. points to an array, not to the type of the array's elements. The types
  43. 'int *' and 'int (*)[4]' are completely different. In the first case,
  44. dereferencing the pointer yields an 'int', in the second an 'int [4]'.
  45. To use the pointer correctly, do the following:
  46.  
  47. #include <stdio.h>
  48.  
  49. int main( void )
  50. {
  51.   int a[4] = { -13, 11, -7, 5 };
  52.   int (*x)[4] = &a;
  53.  
  54.   for (int i = 0; i < 4; i++ )
  55.   {
  56.     printf( "%d\n", (*x)[i] );
  57.   }
  58.   return 0;
  59. }
  60.  
  61. David White
  62. davidw@werple.mira.net.au
  63.